<template>
	<view >
		<view class="idCardCont" @click="open">
<image :style="{width:width+'rpx',height:height+'rpx'}" v-if="Number(isFront) === 1" :src="showData ? showData : photoZ ? photoZ : require('../../static/image/idcard-front.png')" mode=""></image>
			<image :style="{width:width+'rpx',height:height+'rpx'}"  v-else :src="showData ? showData : photoF ? photoF :require('../../static/image/idcard-behind.png')" mode=""></image>
		</view>
		<view class="modal" v-if="isOpen">
			<!-- #ifdef MP-WEIXIN -->
			<page-container class="container" :show="isOpen"  @afterleave="close">
			<!-- #endif -->
			<view class="contant" :style="{'height':windowHeight+'px','width':windowWidth+'px'}">
				<view class="top" v-if="isFront==1">
					(请将身份证 <span style="font-size: 55rpx;
    color: #fb0909;">正面</span> 放入框内)
				</view>
				<view class="top" v-else>
					(请将身份证 <span style="font-size: 55rpx;
    color: #fb0909;">反面</span> 放入框内)
				</view>
				<view class="center">
					<image v-show="isPhoto" class="showImg" mode="widthFix" :src="photoData.tempFilePath"></image>
					<view class="showCamera" v-show="!isPhoto">
						<!-- #ifdef MP-WEIXIN -->
							<camera class="camera" v-if="isSetting"  device-position="back" flash="off" @error="error" @initdone="initdone"></camera>
						<!-- #endif -->
						<image v-if="Number(isFront) === 1" class="zen" mode="widthFix" :src="require('../../static/image/zen.png')"></image>
						<image v-else class="fan" mode="widthFix" :src="require('../../static/image/fan.png')"></image>
					</view>
				</view>
				<view class="bottom"  v-if="isCamera" >
					<view class="longBtn" v-if="!isPhoto" >
							<tn-button backgroundColor="#01BEFF" width="100%"  size="lg" fontColor="#ffffff"  @click="takePhoto">拍照</tn-button>
				
					</view>
					<view class="btn" v-if="isPhoto">
					<tn-button backgroundColor="#bad5de" width="100%" fontColor="#333333" @click="remake">取消</tn-button>
					
					
					</view>
					<view class="btn" v-if="isPhoto">
						<tn-button backgroundColor="#01BEFF" width="100%" fontColor="#ffffff"  @click="upload">确定</tn-button>
					
					</view>
				</view>
			</view>
			<view class="tuichu" @click="close">退出</view>
			<!-- #ifdef MP-WEIXIN -->
			</page-container>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	export default {
	    data() {
	        return {
				isOpen:false,//打开拍照页面
				isPhoto:false,//是否完成拍照
				isSetting:false,//授权
				isCamera:false,//相机初始化
				photoData:null,//拍摄数据,
				showData:'',//显示拍摄数据
	        }
	    },
		props:{
			requestSuccess: Boolean,
			isFront:{
				type:[String,Number], 
				default(){
					return 1 //1正 0反
				}
			},
			width:{
				type:[String,Number], 
				default(){
					return 600
				}
			},
			height:{
				type:[String,Number], 
				default(){
					return 400
				}
			},
			photoZ:{ //正面地址
				type:String,
				default(){
					return ''
				}
			},
			photoF:{ //反面地址
				type:String,
				default(){
					return ''
				}
			},
			cropImage:{ //是否裁剪
				type:Boolean,
				default(){
					return false
				}
			},
			cropScale:{ //裁剪比例
				type: String,
				default(){
					return '16:9'
				}
			}
		},
		watch: {
		  requestSuccess(newVal) {
			
		    if (!newVal) {
			
				
		      // 如果请求失败，将 showData 的值设为空
		      this.showData = '';
		    }
		  }
		},
		computed: {
			windowHeight() {
				var systemInfo = uni.getSystemInfoSync();
				return systemInfo.windowHeight;
			},
			windowWidth() {
				return uni.getSystemInfoSync().windowWidth;
			}
		},
	    methods: {
			 clearShowData() {
			      // 在这里清空数据或重置数据
			      // 例如：
			      this.showData = null;
			    },
			// 检查摄像头授权
			testCamera(){
				let _self = this;
				uni.getSetting({
				   success(res) {
					  if(!res.authSetting['scope.camera']){
					  	  uni.authorize({
					  		  scope: 'scope.camera',
					  		  success(res) {
					  			  _self.testCamera()
					  		  },
					  		  fail(err) {
					  			  uni.showModal({
					  				title: '提示',
									cancelText:"退出",
									confirmText:"去设置",
					  				content: '检测到您没有打开摄像头权限',
					  				success (res) {
					  				  if (res.confirm) {
					  					uni.openSetting({
					  					  success(res) {
					  						 _self.testCamera()
					  					  }
					  					});
					  				  } else if (res.cancel) {
					  						_self.tuichu()
					  				  }
					  				}
					  			  })
					  		  }
					  	  })
					  }  else {
						  _self.isSetting = true
					  }
				   }
				})
			},
			open(){
				let _self = this;
				_self.isOpen = true
				_self.testCamera()
			},
			// 相机初始化完成
			initdone(){
				let _self = this;
				_self.isCamera = true;
			},
			// 退出
			close(){
				let _self = this;
				_self.isOpen = false
				_self.$emit("close",_self.isFront)
			},
			// 拍摄身份证
	        takePhoto() {
	            const ctx = uni.createCameraContext();
				let _self = this;
	            ctx.takePhoto({
	                quality: 'high',
	                success: (res) => {
						if(_self.cropImage && wx.cropImage){ //验证是否支持裁剪功能
							let datas = res
							uni.showModal({
								title: '上传提示',
								showCancel:false,
								content: '请确保您的身份证在黑色裁剪框以内！',
								success: function (res) {
									if (res.confirm) {
										wx.cropImage({
										  src:datas.tempImagePath, // 图片路径
										  cropScale:_self.cropScale,
										  success(res1){
												//获取tempFiles
												if(res1.tempFilePath.indexOf("wxfile://") !== -1){ // 验证地址是否有误
													_self.photoData = {
														tempFilePath:res1.tempFilePath
													}
												} else {
													//获取tempFiles
													_self.photoData = {
														tempFilePath:datas.tempImagePath
													}
												}
												_self.isPhoto = true
										  },
										  complete(res){
											  console.log(res)
										  }
										})
									} 
								}
							});
						} else {
							//获取tempFiles
							_self.photoData = {
								tempFilePath:res.tempImagePath
							}
							_self.isPhoto = true
						}
						
						
	                }
	            });
	        },
			tips(title){
				let timer = setTimeout(()=>{
					clearTimeout(timer)
					timer = null
					uni.showToast({
						title,
						icon:"none",
						duration:2000
					})
				},500)
			},
			// 在小程序中显示临时文件图片
			upload(item) {
			    let _self = this;
			    let a = JSON.parse(JSON.stringify(_self.photoData));
			    console.log(a, 'a');
			
			    // 使用 wx.getImageInfo 获取临时文件信息
			    wx.getImageInfo({
			        src: a.tempFilePath,
			        success(res) {
						console.log(res,'res')
			            // 将临时文件转换成 base64 格式
			            wx.getFileSystemManager().readFile({
			                filePath: a.tempFilePath,
			                encoding: 'base64',
			                success(base64Res) {
								console.log(base64Res.data,'console.log(base64Res.data)')
			                    // 在下一个 Vue 渲染周期时执行赋值和事件触发
			                    _self.$nextTick(() => {
			                        _self.showData = 'data:image/jpeg;base64,' + base64Res.data;
									console.log(_self.showData,'_self.showData')
			                        let datas = JSON.parse(JSON.stringify(_self.photoData));
			                        datas['isFront'] = _self.isFront;
			                        _self.$emit("idCardData", datas);
			                        _self.isOpen = false;
			                    });
			                },
			                fail(error) {
			                    console.error('读取临时文件失败', error);
			                }
			            });
			        },
			        fail(error) {
			            console.error('获取临时文件信息失败', error);
			        }
			    });
			},

			// // 身份证识别
			// upload(item){
			// 	let _self = this;
			// 	// let a=JSON.parse(JSON.stringify(_self.photoData));
				
				
			// 	// console.log(a,'a')
			// 	    _self.$nextTick(() => {
			// 	        _self.showData = JSON.parse(JSON.stringify(_self.photoData));
			// 	        let datas = JSON.parse(JSON.stringify(_self.photoData));
			// 	        datas['isFront'] = _self.isFront;
			// 	        _self.$emit("idCardData", datas);
			// 	        _self.isOpen = false;
			// 	    });
			// 	// _self.showData = JSON.parse(JSON.stringify(_self.photoData))
			// 	// let datas = JSON.parse(JSON.stringify(_self.photoData))
			// 	// datas['isFront'] = _self.isFront
			// 	// _self.$emit("idCardData",datas)
			// 	// _self.isOpen = false
			// },
			// 重拍
			remake(){
				let _self = this;
				_self.isPhoto = false
			},
	        error(e) {
	            console.log(e.detail);
	        }
	    }
	}
</script>

<style scoped lang="scss">
.idCardCont{
	text-align: center;
}
.modal{
	position: fixed;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
}
.contant{
	padding-top: 100rpx;
	background-color: #fff;
		.top{
			padding: 20rpx;
			text-align: center;
			    font-size: 38rpx;
			  
			    color: #73660a;
		}
		.center{
			 position: relative;
			 width: 750rpx;
			 height: 444rpx;
			 overflow: hidden;
			 .showCamera{
				 width: 100%;
				 height: 100%;
				.camera{
						 width: 100%;
						 height:100%;
				}
				.zen,.fan{
						 position: absolute;
						 left: 0;
						 right: 0;
						 top: 0;
						 bottom: 0;
						 margin: auto;
						 width: 90%;
						 border-radius: 20rpx;
						 box-shadow: 0 0 20rpx 50rpx rgba(0,0,0,.5);
				}
			 }
			 .showImg{
				 width: 100%;
				 height:100%;
			 }
		}
		.bottom{
			 display: flex;
			 align-items: center;
			 justify-content: center;
			 padding: 40rpx 20rpx 0;
			 box-sizing: border-box;
			 .btn{
				 width: 300rpx;
				 &:nth-child(1){
					 margin-right: 20rpx;
				 }
			 }
			 .longBtn{
				 width: 100%;
				 .tn-btn-class tn-btn{
					 width: 100%;
				 }
			 }
		}
	}
	.tuichu{
		position: fixed;
		right: 40rpx;
		bottom: 40rpx;
		width: 100rpx;
		height: 100rpx;
		line-height: 100rpx;
		font-size: 28rpx;
		text-align: center;
		border-radius: 50%;
		background-color: #fff;
		box-shadow: 0 0 10rpx 4rpx rgba(59,154,251,.2);
	}
</style>
